package cn.dubito.miaosha.controller;

import cn.dubito.miaosha.controller.vo.Result;
import cn.dubito.miaosha.domain.SeckillUser;
import cn.dubito.miaosha.redis.GoodsKey;
import cn.dubito.miaosha.redis.RedisService;
import cn.dubito.miaosha.service.GoodsService;
import cn.dubito.miaosha.vo.GoodsDetailVO;
import cn.dubito.miaosha.vo.GoodsVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author liliang
 * @description:
 * @date 2018/3/31.
 */
@RequestMapping("/goods")
@Controller
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    @Autowired
    private ApplicationContext applicationContext;

    private static final String USER_LOGIN = "user";
    private static final String TO_LOGIN = "login";
    private static final String TO_GOODS_LIST = "goods_list";
    private static final String GOODS_LIST = "goodsList";
    private static final String GOODS_DETAIL = "goods_detail";
    private static final String GOODS = "goods";
    private static final String SECKILL_STATUS = "seckillStatus";
    private static final String COUNTDOWN = "remainSeconds";
    private static final int SECKILL_END = 2;
    private static final int SECKILL_NOT_BEGIN = 0;
    private static final int SECKILL_IN = 1;


    /**
     * 缓存整个HTML文件
     *
     * @param request
     * @param response
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(value = "/goods_list", produces = "text/html")
    @ResponseBody
    public String toGoods(HttpServletRequest request, HttpServletResponse response, Model model, SeckillUser user) {
        if (user == null) {
            return "登录过期,请重新登录";
        }
        model.addAttribute(USER_LOGIN, user);
        String html = redisService.get(GoodsKey.getByGoodsList, "", String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }

        List<GoodsVO> goodsVOS = goodsService.listGoodsVo();
        model.addAttribute(GOODS_LIST, goodsVOS);
//        return TO_GOODS_LIST;

        SpringWebContext webContext = new SpringWebContext(request, response,
                request.getServletContext(),
                request.getLocale(),
                model.asMap(), applicationContext);
        html = thymeleafViewResolver.getTemplateEngine().process(TO_GOODS_LIST, webContext);
        if (!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.getByGoodsList, "", html);
        }
        return html;
    }

    /**
     * 缓存整个HTML文件
     *
     * @param request
     * @param response
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/detail2/{goodsId}", produces = "text/html")
    @ResponseBody
    public String toGoodsDetail2(HttpServletRequest request, HttpServletResponse response,
                                 Model model, SeckillUser user, @PathVariable("goodsId") long goodsId) {
        if (user == null) {
            return TO_LOGIN;
        }
        String html = redisService.get(GoodsKey.getByGoodsDetail, "", String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        model.addAttribute(USER_LOGIN, user);
        GoodsVO goods = goodsService.getGoodsDetailByGoodsId(goodsId);
        model.addAttribute(GOODS, goods);
        long startTime = goods.getStartDate().getTime();
        long endTime = goods.getEndDate().getTime();
        long nowTime = System.currentTimeMillis();
        int seckillStatus = SECKILL_NOT_BEGIN;
        int remainSeconds;
        if (nowTime < startTime) {
            // 未开始
            remainSeconds = (int) ((startTime - nowTime) / 1000);
        } else if (nowTime > endTime) {
            // 结束
            seckillStatus = SECKILL_END;
            remainSeconds = -1;
        } else {
            // 进行中
            seckillStatus = SECKILL_IN;
            remainSeconds = 0;
        }
        model.addAttribute(SECKILL_STATUS, seckillStatus);
        model.addAttribute(COUNTDOWN, remainSeconds);
//        return GOODS_DETAIL;
        SpringWebContext webContext = new SpringWebContext(request, response,
                request.getServletContext(),
                request.getLocale(),
                model.asMap(), applicationContext);
        html = thymeleafViewResolver.getTemplateEngine().process(GOODS_DETAIL, webContext);
        if (!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.getByGoodsDetail, String.valueOf(goodsId), html);
        }
        return html;
    }


    /**
     * 静态分离
     *
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVO> toGoodsDetail(SeckillUser user, @PathVariable("goodsId") long goodsId) {

        GoodsVO goods = goodsService.getGoodsDetailByGoodsId(goodsId);
        long startTime = goods.getStartDate().getTime();
        long endTime = goods.getEndDate().getTime();
        long nowTime = System.currentTimeMillis();
        int seckillStatus = SECKILL_NOT_BEGIN;
        int remainSeconds = -1;
        if (nowTime < startTime) {
            // 未开始
            remainSeconds = (int) ((startTime - nowTime) / 1000);
        } else if (nowTime > endTime) {
            // 结束
            seckillStatus = SECKILL_END;
            remainSeconds = -1;
        } else {
            // 进行中
            seckillStatus = SECKILL_IN;
            remainSeconds = 0;
        }
        GoodsDetailVO detailVO = new GoodsDetailVO();
        detailVO.setGoods(goods);
        detailVO.setRemainSeconds(remainSeconds);
        detailVO.setSeckillStatus(seckillStatus);
        detailVO.setUser(user);
        return Result.success(detailVO);
    }

}
